package leetcode_acm.array;

/**
 * 功能描述
 *
 * @author: 张庭杰
 * @date: 2023年03月20日 21:28
 */
public class SpiralOrder {
    public int[] spiralOrder(int[][] matrix){
        if(matrix == null || matrix.length == 0){
            return new int[]{};
        }
        int n = matrix.length;
        int m = matrix[0].length;
        int[] ans = new int[n*m+1];
        int leftBound = 0,rightBound = m-1,topBound = 0,bottomBound = n-1;
        int count = 0,bound = n*m+1;
        while (count != bound){
            //从左到右走
            if(topBound <= bottomBound){
                for(int i = leftBound;i<=rightBound;i++){
                    ans[count++] = matrix[topBound][i];
                }
                topBound++;
            }
            //从上到下走
            if(leftBound <= rightBound){
                for(int i = topBound;i <= bottomBound;i++){
                    ans[count++] = matrix[i][rightBound];
                }
                rightBound--;
            }
            //从右到左走
            if(topBound <= bottomBound){
                for(int i = rightBound;i>=leftBound;i--){
                    ans[count++] = matrix[bottomBound][i];
                }
                bottomBound--;
            }
            //从下到上走
            if(leftBound <= rightBound){
                for(int i = bottomBound;i>=topBound;i--){
                    ans[count++] = matrix[i][leftBound];
                }
                leftBound++;
            }
        }
        return ans;
    }
}
